﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Linq;
using Microsoft.TeamFoundation.VersionControl.Client;
using System.Collections.ObjectModel;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Framework.Client;
using Microsoft.TeamFoundation.Framework.Common;
using System.Threading;
using System.Data.Entity;
using Wicresoft.Task.Common;

namespace Wicresoft.Task.TFSAutoNotify
{
    class AutoNotify
    {
        static Tfs_AutoNotifyEntities tfsDB = new Tfs_AutoNotifyEntities();
        public static void Notify()
        {

            try
            {
                Uri configurationServerUri = new Uri("http://ws-fs-01:8080/tfs/mylab");
                List<RegisteredProjectCollection> projectCollections;
                TfsConfigurationServer configurationServer = TfsConfigurationServerFactory.GetConfigurationServer(configurationServerUri);
                projectCollections = new List<RegisteredProjectCollection> { RegisteredTfsConnections.GetProjectCollection(configurationServerUri) };
                var registeredProjectCollection = projectCollections[0];
                var projectCollection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(registeredProjectCollection);
                var versionControl = projectCollection.GetService<VersionControlServer>();
                var teamProjects = new List<TeamProject>(versionControl.GetAllTeamProjects(false));
                //for (int i = 0; i < teamProjects.Count; i++)
                //{
                //    Console.WriteLine(teamProjects[i].Name);
                //}
                Shelveset[] shelveSet =
                versionControl.QueryShelvesets("", "");
                SaveShelveSet(shelveSet);               
                DeleteShelveSetIfMoreThan(shelveSet, versionControl, 30);      
            }
            catch (Exception x)
            {
                Console.WriteLine(x.Message);
                LogRunInfo.Write(x.Message);
            }


        }
        public static void CheckInIfApproved(string title,string name,bool ifSuccessDelete,VersionControlServer server)
        {
            ShelvesetCheckInParameters checkin = new ShelvesetCheckInParameters(title,name);
            checkin.DeleteShelveset = ifSuccessDelete;
            server.CheckInShelveset(checkin);
        }
        public static void DeleteShelveSetIfMoreThan(Shelveset[] sets, VersionControlServer server, int timeDay)
        {
            foreach (Shelveset s in sets)
            {
                DateTime x = System.DateTime.Now.AddDays(-timeDay);
                if (s.CreationDate <= x)
                {
                    server.DeleteShelveset(s);
                }
            }
        }
        public static void SaveShelveSet(Shelveset[] sets)
        {


            foreach (Shelveset s in sets)
            {
                //if (s.WorkItemInfo.Count() != 0)
                //{
                //    Console.WriteLine(s.WorkItemInfo.First().WorkItem.Uri);
                //}
                if (!IsExist(s.Name, tfsDB.ShelveInfos.ToList()))
                {
                    ShelveInfo _shelve = CreateShelveInfo(s);
                    if (_shelve != null)
                    {
                        if (_shelve.MailTo != null)
                        {
                            if (_shelve.MailTo.Contains("@"))
                            {
                                tfsDB.ShelveInfos.Add(_shelve);
                                LogRunInfo.Write("New Shelveset be added,It's Name is " + _shelve.Title);
                            }
                        }
                    }

                }
                if (tfsDB.ShelveInfos.ToList().Count == 0)
                {
                    ShelveInfo _shelve = CreateShelveInfo(s);
                    if (_shelve != null)
                    {
                        if (_shelve.MailTo != null)
                        {
                            if (_shelve.MailTo.Contains("@"))
                            {
                                tfsDB.ShelveInfos.Add(_shelve);
                                LogRunInfo.Write("New Shelveset Be Added,It's Name Is " + _shelve.Title);
                            }
                        }
                    }
                }
                tfsDB.SaveChanges();

            }

        }
        public static ShelveInfo CreateShelveInfo(Shelveset s)
        {
            string tempLink = "";
            string tempBody = "";
            try
            {
                tempLink = File.ReadAllText("Link.txt");
                tempBody = File.ReadAllText("Body.txt");
            }
            catch (Exception x)
            {
                LogRunInfo.Write(x.Message);
            }
            ShelveInfo _shelve = new ShelveInfo();
            string itemInfor = "";
            int i = s.WorkItemInfo.Count();
            if (i == 0)
            {
                itemInfor = "Untouched";
            }
            for (int j = 0; j < i; j++)
            {
                var _x = s.WorkItemInfo[j].WorkItem;
                string _y = string.Format(tempLink, _x.Id, _x.Id, _x.Title);
                if (j == i - 1)
                {
                    itemInfor = itemInfor + _y;
                }
                else
                {
                    itemInfor = itemInfor + _y + ",";
                }
            }
            string codeReviewer = s.CheckinNote.Values.First(p => p.Name == "Code Reviewer").Value;
            if (codeReviewer.Trim().Length == 0)
            {
                _shelve.IsSent = true;
            }
            else
            {
                _shelve.IsSent = false;

            }
            string mailTo = QueryMailTo(codeReviewer);
            if (mailTo == "")
            {
                LogRunInfo.Write("You Write An Invalid Code Reviewer：" + codeReviewer);
            }
            else
            {
                string codeReviewerEnglishName = tfsDB.EmployeesInfos.First(p => p.Email == mailTo).EnglishName;
                string comment = (s.Comment == null) ? "Unwrite" : s.Comment;
                string body = string.Format(tempBody, codeReviewerEnglishName, s.Name, s.OwnerName.TrimStart(), codeReviewerEnglishName.TrimStart(), itemInfor.TrimStart(), s.Comment.TrimStart());
                _shelve.Title = s.Name;
                _shelve.Owner = s.OwnerName;
                _shelve.CreateTime = s.CreationDate;
                _shelve.SentTime = DateTime.MaxValue;
                _shelve.MailFrom = "noreply@ws-fs-01.local";
                _shelve.MailTo = mailTo;
                EmployeesInfo _Es = tfsDB.EmployeesInfos.First(p => _shelve.Owner.Contains(p.Ad4Account));
                _shelve.CC = "milesch@wicresoft.com;helenj@wicresoft.com" + ";" + _Es.Email;
                _shelve.BCC = "i-jibw@wicresoft.com";
                _shelve.Subject = "Code Review Request For  " + s.Name;
                _shelve.Body = body;
            }
            return _shelve;
        }
        public static bool IsExist(string _info, List<ShelveInfo> _list)
        {
            bool y = false;
            foreach (ShelveInfo x in _list)
            {
                if (x.Title.Equals(_info))
                {
                    y = true;
                }

            }
            return y;
        }
        public static string QueryMailTo(string codeReviewer)
        {
            string email = "";
            var employeesInfo = tfsDB.EmployeesInfos.ToList();
            foreach (var x in employeesInfo)
            {
                if (codeReviewer.Trim().Length != 0)
                {
                    if (IsWho(x, codeReviewer))
                    {
                        email = x.Email;
                    }
                }
            }
            return email;

        }
        public static bool IsWho(EmployeesInfo p, string codeReviewers)
        {
            bool x = false;

            string codeReviewer = codeReviewers.Trim();
            if (p.Name.Trim().Contains(codeReviewer))
            {
                x = true;
            }

            if (p.EnglishName.Trim().Equals(codeReviewer, StringComparison.OrdinalIgnoreCase))
            {
                x = true;
            }
            if (p.PinYin.Trim().ToLower().Contains(codeReviewer.ToLower()))
            {
                x = true;
            }

            if (p.Ad4Account.Trim().ToUpper().Contains(codeReviewer.ToUpper()))
            {
                x = true;

            }
            return x;
        }

        public static bool IsExist(string info, string owner, DateTime createTime)
        {

            return tfsDB.ShelveInfos.Count(p => p.Title == info && p.CreateTime == createTime && p.Owner == owner) >= 1;


        }
    }
}

